#include "cloud.h"

#include "explosion.h"
#include "texture.h"


CCloud::CCloud()
{
	isExplosion = false;

	cloudParticles = NULL;
	cloudParticles = NULL;
	cloudTexture = new CTexture;

	Load();
}

CCloud::~CCloud()
{
	if (cloudParticles != NULL)
	{
		cloudParticles->KillSystem();
		delete [] cloudParticles;
		cloudParticles = NULL;
	}

	if (dyingParticles != NULL)
	{
		dyingParticles->KillSystem();
		delete [] dyingParticles;
		dyingParticles = NULL;
	}

	if (cloudTexture != NULL)
	{
		delete cloudTexture;
		cloudTexture = NULL;
	}
}

void CCloud::SetupCloudTexture()
{
	glGenTextures(1, &cloudTexture->texID);
	glBindTexture(GL_TEXTURE_2D, cloudTexture->texID);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, cloudTexture->width, cloudTexture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, cloudTexture->data);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 4, cloudTexture->width, cloudTexture->height, GL_RGBA, GL_UNSIGNED_BYTE, cloudTexture->data);
}

void CCloud::OnAnimate(scalar_t deltaTime)
{
	float cosYaw = (float)cos(DEG2RAD(direction));
	float sinYaw = (float)sin(DEG2RAD(direction)); 

	float speed = velocity.z * deltaTime;

	position.x += float(cosYaw)*speed;
	position.z += float(sinYaw)*speed;

	distanceTravel += position.Length();

	//if (isExplosion)
	//{
	//	cloudParticles->Update(deltaTime);
	//	dyingParticles->Update(deltaTime);
	//}
}

void CCloud::OnCollision(CObject *collisionObject)
{
	position.y = 200.0;
	
	if (!isExplosion)
	{
		isExplosion = true;
		velocity = CVector(0.0, 0.0, 0.0);
		cloudParticles = new CExplosion(250, position, 50.0, cloudTexture->texID);
		dyingParticles = new CExplosion(1, position, 10.0, cloudTexture->texID);
	}
}

void CCloud::OnDraw(CCamera *camera)
{
	// Render the cloud texture
	if (isExplosion)
	{
		glDisable(GL_FOG);
		cloudParticles->Render();
		//dyingParticles->Render();
		glEnable(GL_FOG);
	}
}


void CCloud::Load()
{
	CMD2Model::Load("..\\..\\res\\models\\rocketair.md2", "..\\..\\res\\models\\rocket.pcx");
	cloudTexture->LoadTexture("..\\..\\res\\cloud.bmp");
	SetupCloudTexture();
}

void CCloud::Unload()
{
}

void CCloud::OnPrepare()
{
	// perform collision detection from this entity with all other objects in world
	ProcessCollisions(FindRoot());

	if (isExplosion)
	{
		if (cloudParticles->IsHalfOver())
		{
			delete [] dyingParticles;
			dyingParticles = NULL;
			dyingParticles = cloudParticles;

			cloudParticles = NULL;
			cloudParticles = new CExplosion(250, position, 50.0, cloudTexture->texID);
		}
	}
}
